<template>
	<view class="cat2bug-body">
		<page-header :team-id="teamId" :disabled="true" :show-back-button="true"></page-header>
		<page-body class="task-body">
			<template v-slot:content>
				<uni-forms v-if="loaded" ref="form" :modelValue="formData" :rules="rules" :label-width="80" label-align="right" label-position="top">
					<uni-forms-item :label="$t('defect.task-name')" name="defectName" required>
						<uni-easyinput type="text" v-model="formData.defectName" :placeholder="$t('defect.enter-name')" maxlength="128" />
					</uni-forms-item>
					<uni-forms-item :label="$t('priority')" name="defectLevel" required>
						<defect-level-picker v-model="formData.defectLevel"></defect-level-picker>
					</uni-forms-item>
					<uni-forms-item :label="$t('handle-by')" name="handleBy" required>
						<member-picker v-model="formData.handleBy" @open="hideTools" @close="showTools"></member-picker>
					</uni-forms-item>
					<uni-forms-item :label="$t('module')" name="moduleId">
						<module-picker v-model="formData.moduleId" @open="hideTools" @close="showTools"></module-picker>
					</uni-forms-item>
					<uni-forms-item :label="$t('plan-time')">
						<uni-datetime-picker v-model="planTimeRange" type="datetimerange" rangeSeparator="至" @show="hideTools" @change="showTools" @maskClick="showTools" />
					</uni-forms-item>
					<uni-forms-item :label="$t('describe')" name="defectDescribe">
						<uni-easyinput type="textarea" autoHeight v-model="formData.defectDescribe" :placeholder="$t('defect.enter-describe').toString()" maxlength="65535"></uni-easyinput>
					</uni-forms-item>
					<uni-forms-item :label="$t('option')">
						<template>
							<view class="col form-cache-switch">
								<switch :checked="isSaveFormCache" @change="handleSaveFormCache" />
								<text class="form-item-description">{{ $t('defect.added-save-form-cache') }}</text>
							</view>
						</template>
					</uni-forms-item>
					<uni-forms-item :label="$t('image')" name="imgUrls">
						  <upload-image v-model="formData.imgUrls" />
					</uni-forms-item>
					<uni-forms-item :label="$t('annex')" name="annexUrls">
						<upload-file v-model="formData.annexUrls" />
					</uni-forms-item>
				</uni-forms>
			</template>
			<template v-slot:footer>
				<view class="body-footer"></view>
			</template>
		</page-body>
		<page-footer>
			<view class="row full-width" v-show="toolsVisible">
				<button class="save-defect tools-button left" type="primary" @click="handleSubmitTask">{{ $t('defect.save-task') }}</button>
				<t-t-s class="tts" @input="handleTts">
					<button class="tools-button right" type="default"><uni-icons type="mic" size="35"></uni-icons></button>
				</t-t-s>
			</view>
		</page-footer>
	</view>
</template>

<script>
	import { makeDefect } from "@/api/ai/AiDefect"
	import {addDefect, updateDefect} from "@/api/system/defect";
	import config from '@/config'
	import TTS from "@/subpackage/components/stt/index.vue"
	import MemberPicker from "@/components/member/member-picker/index.vue"
	import DefectLevelPicker from "@/components/defect/defect-level-picker/index.vue"
	import ModulePicker from "@/components/module/module-picker/index.vue"
	import UploadImage from "@/components/upload-image/index.vue"
	import UploadFile from "@/components/upload-file/index.vue"
	import {DEFECT_TYPE_TASK} from "@/utils/defect.js"
	// 是否保存缺陷添加表单缓存的key键值
	const IS_SAVE_FORM_CACHE_KEY = 'defect-is-save-add-form-cache';
	// 缺陷添加表单缓存的key键值
	const FORM_CACHE_KEY = 'defect-add-task-form-cache';
	
	export default {
		name: 'AddTask',
		components: { TTS, MemberPicker, DefectLevelPicker, ModulePicker, UploadImage, UploadFile },
		data() {
			return {
				// 表单数据
				formData: {
					defectType: DEFECT_TYPE_TASK,
					moduleId: 0,
					imgUrls: '',
					annexUrls: '',
					handleBy: []
				},
				// 表单中的计划时间
				planTimeRange: [],
				// 表单规则
				rules: {
					defectName: {
						rules: [{
							required: true,
							errorMessage: this.$i18n.t('defect.defect-name-cannot-empty'),
						}]
					},
					defectLevel: {
						rules: [{
							required: true,
							errorMessage: this.$i18n.t('defect.defect-level-cannot-empty')
						}]
					},
					handleBy: {
						rules: [{
							required: true,
							errorMessage: this.$i18n.t('defect.handle-by-cannot-empty')
						}]
					},
				},
				// 是否缓存表单数据，用于下次新建时免填
				isSaveFormCache: false,
				// 是否显示TTS组件
				toolsVisible: true,
			}
		},
		computed: {
			uploadUrl() {
				return config.baseUrl + "/common/upload";
			},
			/** 当前团队ID */
			teamId() {
			    return this.$store.state.user.config.currentTeamId;
			},
			/** 当前项目名称 */
			projectId() {
			    return this.$store.state.user.config.currentProjectId;
			},
			/** 获取当前成员id */
			currentMemberId() {
				return this.$store.state.user.id;
			},
			loaded() {
				return this.$i18n.locale?true:false;
			}
		},
		onShow() {
			this.readIsSaveFormCacheValue();
			if(this.isSaveFormCache) {
				this.readAddFormCache();
			}
		},
		methods: {
			/** 显示工具组件 */
			showTools(){
				this.toolsVisible=true;
			},
			/** 隐藏工具组件 */
			hideTools(){
				this.toolsVisible=false;
			},
			/** 处理保存表单缓存开关状态改变的操作 */
			handleSaveFormCache(e) {
				this.isSaveFormCache = e.detail.value;
				this.saveIsSaveFormCacheValue();
			},
			handleTts(value) {
				if(!value.text) {
					return;
				}
				switch(value.button) {
					case 'bottom':
						this.$set(this.formData, 'defectDescribe', value.text);
						break;
					case 'right':
						const query = {
							describe: value.text,
							projectId: this.projectId
						}
						uni.showLoading({
							title: this.$i18n.t('case.load-prompted')
						})
						makeDefect(query).then(res=>{
							uni.hideLoading();
							const defect = res.data;
							if(defect.defectName) {
								this.$set(this.formData, 'defectName', defect.defectName);
							}
							if(defect.defectDescribe) {
								this.$set(this.formData, 'defectDescribe', defect.defectDescribe);
							}
						}).catch(err=>{
							uni.hideLoading();
						});
						break;
				}
			},
			/** 创建或更新 */
			handleSubmitTask() {
				this.$refs.form.validate().then(res=>{
					this.formData.projectId = this.projectId;
					if(this.planTimeRange && this.planTimeRange.length>1) {
						this.formData.planStartTime = this.planTimeRange[0];
						this.formData.planEndTime = this.planTimeRange[1];
					}
					const self = this;
					if (this.formData.defectId != null) {
						updateDefect(this.formData).then(res => {
							uni.navigateBack({
								success: function(res) {
									uni.$emit('defect-modify');
								}
							});
						});
					} else {
						addDefect(this.formData).then(res => {
							uni.navigateBack({
								success: function(res) {
									uni.$emit('defect-add');
								}
							});
						});
					}
					this.saveAddFormCache();
				}).catch(err =>{
					console.log('表单错误信息：', err);
				})
			},
			/** 读取是否添加的表单本地缓存的开关选项 */
			readIsSaveFormCacheValue() {
				this.isSaveFormCache = uni.getStorageSync(IS_SAVE_FORM_CACHE_KEY);
			},
			/** 获取是否添加的表单本地缓存的开关选项 */
			saveIsSaveFormCacheValue() {
				uni.setStorageSync(IS_SAVE_FORM_CACHE_KEY, this.isSaveFormCache);
			},
			/** 获取添加的表单本地缓存 */
			readAddFormCache() {
				const cacheForm = uni.getStorageSync(FORM_CACHE_KEY)||{};
				if(cacheForm) {
					this.formData.defectLevel = cacheForm.defectLevel;
					this.formData.handleBy = cacheForm.handleBy;
					this.formData.moduleVersion = cacheForm.moduleVersion;
					this.formData.moduleId = cacheForm.moduleId;
					this.planTimeRange = cacheForm.planTimeRange;
				}
			},
			/** 保存添加表单本地缓存 */
			saveAddFormCache() {
				if(this.isSaveFormCache) {
					uni.setStorageSync(FORM_CACHE_KEY, {
						defectLevel: this.formData.defectLevel,
						handleBy: this.formData.handleBy,
						moduleVersion: this.formData.moduleVersion,
						moduleId: this.formData.moduleId,
						planTimeRange: this.planTimeRange
					});
				}
			},
		}
	}
</script>

<style lang="scss" scoped>
	.task-body {
		border-top: 6rpx solid $c2d-color-task;
	}
	::v-deep .uni-forms {
		margin: 0 20rpx 20rpx 20rpx;
		padding-top: 20rpx;
	}
	.bottom-tools {
		width: 100%;
		position: absolute;
		margin: 0rpx 0rpx env(safe-area-inset-bottom) 0rpx;
		bottom: 0;
	}
	.save-defect {
		margin: 0;
		flex: 1;
		background-color: $c2d-color-task;
	}
	.tts {
		flex-shrink: 0;
	}
	.tools-button {
		height: 100rpx;
		display: inline-flex;
		align-items: center;
		justify-content: center;
	}
	.left {
		border-top-left-radius: 0;
		border-bottom-left-radius: 0;
	}
	::v-deep .right {
		width: 300rpx;
		border-top-right-radius: 0;
		border-bottom-right-radius: 0;
	}
	.form-cache-switch {
		margin-top: 20rpx;
	}
	.form-item-description {
		font-size: $uni-font-size-sm;
		color: $uni-text-color-disable;
	}
	.body-footer {
		width: 100%;
		height: calc(env(safe-area-inset-bottom) + 100rpx);
	}
</style>